#/bin/env python


from twisted.internet import protocol, reactor, defer
from twisted.protocols import basic
from twisted.internet.protocol import ClientCreator
from twisted.protocols import amp
from ampserver import MongoQuery

import test_pb2


class ProxyProtocol(basic.LineReceiver):
    def lineReceived(self, line):
        pb_object = test_pb2.Book()
        pb_object.ParseFromString(line)
        print type(pb_object.book_name)
        print type(pb_object.author)
        d = self.factory.mongoSevice(pb_object.book_name,pb_object.author)

        def onError(err):
            return 'Internal error in server',err
        d.addErrback(onError)

        def writeResponse(message):
            print message
            self.transport.write(message['result']+'\r\n')
            self.transport.loseConnection()
        d.addCallback(writeResponse)

class ProxyFactory(protocol.ServerFactory):
    protocol = ProxyProtocol

    def __init__(self, **kwargs):
        pass

    def mongoSevice(self,bname,bauthor):
        d1 = ClientCreator(reactor, amp.AMP).connectTCP('127.0.0.1', 1234).addCallback(lambda p: p.callRemote(MongoQuery, book_name, author))
        def done(result):
            print 'mongo operation done', result
            return result
        #return defer.DeferredList([d1]).addCallback(done)
        return d1.addCallback(done)




reactor.listenTCP(1079,ProxyFactory(moshez='Happy and well'))
reactor.run()


# vim: st=2 sts=2 sw=2 noet

